<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import the Joomla modellist library
jimport('joomla.application.component.modellist');
/**
 * ProductList Model
 */
class ProductModelProducts extends JModelList
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param	string	An optional ordering field.
	 * @param	string	An optional direction (asc|desc).
	 */
	protected function populateState($ordering = null, $direction = null) {
		// Initialise variables.
		$context	= $this->context;
		$search = $this->getUserStateFromRequest($context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);
	
		// List state information.
		parent::populateState('a.modified', 'DESC');
	}
	
	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return      string  An SQL query
	 */
	protected function getListQuery() {
		// Create a new query object.
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);
		
		// Select some fields
		$query->select('a.id, a.code, a.name, a.published, a.featured, c.title as category, a.description, a.modified');
		
		// From the products table
		$query->from('#__product as a');
		$query->leftJoin('#__categories as c on a.catid=c.id');
		
		// Filter by search in title
		$search = $this->getState('filter.search');
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$query->where('a.id = ' . (int)substr($search, 3));
			} else {
				$search = $db->quote('%' . $db->escape($search, true) . '%');
				$query->where('(a.name LIKE ' . $search . ' OR a.code LIKE ' . $search . ')');
			}
		}
		
		// Add the list ordering clause
		$listOrdering = $db->escape($this->getState('list.ordering', 'a.modified'));
		$listDirn = $db->escape($this->getState('list.direction', 'DESC'));
		$query->order($listOrdering . ' ' . $listDirn);

		return $query;
	}
	
	/**
	 * Method to toggle the featured setting of products.
	 *
	 * @param	array	The ids of the items to toggle.
	 * @param	int		The value to toggle to.
	 *
	 * @return	boolean	True on success.
	 */
	public function featured($pks, $value = 0) {
		// Sanitize the ids.
		$pks = (array) $pks;
		JArrayHelper::toInteger($pks);
	
		if (empty($pks)) {
			$this->setError(JText::_('COM_CONTENT_NO_ITEM_SELECTED'));
			return false;
		}
	
		//$table = $this->getTable('Featured', 'ProductTable');
	
		try {
			$db = $this->getDbo();
			$db->setQuery(
					' UPDATE #__product' .
					' SET featured = ' . (int) $value .
					' WHERE id IN (' . implode(',', $pks) . ')'
			);
			if (!$db->query()) {
				throw new Exception($db->getErrorMsg());
			}	
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return false;
		}
	
		//$table->reorder();
	
		$this->cleanCache();
		
		return true;
	}
}